package part2;

import part1.tw.ListNode;

/**
 * @Author: shaochong
 * @Date: 2021/8/16
 * @Description:
 */
public class Solution160 {
    private class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int len1 = 0, len2 =0;
        for (ListNode p = headA; p.next != null ; p = p.next) {
            len1++;
        }

        for (ListNode p = headB; p.next != null ; p = p.next) {
            len2++;
        }

        ListNode longLink = len1 > len2 ? headA : headB;
        ListNode shortLink = len1 > len2 ? headB : headA;

        int sub = Math.abs(len1 - len2);
        for (int i = 0; i < sub; i++) {
            longLink = longLink.next;
        }

        while (longLink != null && shortLink != null) {
            if (longLink == shortLink) {
                return longLink;
            }
            longLink = longLink.next;
            shortLink = shortLink.next;
        }
        return null;
    }
}
